/**
 *
 */
package cn.hg.jfsa.manage.controller.system;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.jfsa.core.JfsaThreadLocal;
import cn.hg.jfsa.manage.controller.system.validator.ResourceValidator;
import cn.hg.jfsa.manage.service.JfsaResourceService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.model.JfsaResource;

/**
 * @author Golly
 */
public class JfsaResourceController extends BaseController {

	/**
	 * 资源服务
	 */
	@Inject
	private JfsaResourceService resourceService;

	/**
	 * 跳转到新增页面
	 */
	public void add () {
		Integer parentId = this.getParaToInt("parentId", 0);
		JfsaResource parent = new JfsaResource().setParentId(0).put("parent_name", "").setSortNum(0);

		if (parentId > 0) {
			parent = JfsaResource.DAO.findById(parentId);
		}

		// 创建新记录
		this.setAttr("resource", new JfsaResource().setParentId(parentId).put("parent_name", parent.getName()));
	}

	/**
	 * Ajax删除功能
	 */
	@Before (EvictInterceptor.class)
	@CacheName ("jfsaResource")
	public void ajaxDel () {
		// 通过页面传入的ID查找到记录
		JfsaResource bean = JfsaResource.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {
				JfsaResourceController.this.resourceService.del(bean, true);
				// 更新父对象的子对象ID列表
				JfsaResourceController.this.resourceService
					.updateChildredIds(JfsaResource.DAO.findById(bean.getParentId()));
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式获取机构树
	 */
	@Before (POST.class)
	public void ajaxGetResourceTree () {
		this.renderJson(this.resourceService.getTree());
	}

	/**
	 * Ajax方式新建或更新记录
	 */
	@Before ({
		ResourceValidator.class, EvictInterceptor.class
	})
	@CacheName ("jfsaResource")
	public void ajaxSaveOrUpdate () {
		// 获取页面传入的Bean
		JfsaResource bean = this.getBean(JfsaResource.class, "resource");

		if (bean.getParentId().equals(bean.getId())) {
			this.renderAjaxFailed("1", "上级资源不能是自己！");
			return;
		}

		JfsaAdmin currAdmin = JfsaThreadLocal.getAdmin();
		JfsaResource parent = JfsaResource.DAO.findById(bean.getParentId());
		// 这里引用事务处理是为了方便Ajax模式处理
		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {

				if (null == bean.getId()) {
					// 初始化数据
					bean.setCreatedTime(new Date()).setCreatorId(currAdmin.getId())
						.setEditorId(currAdmin.getId()).setEditedTime(new Date())
						.setPathIds(parent == null ? ""
							: parent.getPathIds() + (parent.getPathIds().length() > 0 ? "," : "")
								+ parent.getId())
						.setLayerNum(null == parent ? 0 : parent.getLayerNum() + 1);

					if (!"action".equals(bean.getType())) {
						bean.setIsLog(false);
					}

					// 新建记录
					bean.save();
				} else {
					// 更新记录
					bean.setEditorId(currAdmin.getId())
						.setEditedTime(new Date());

					if (!"action".equals(bean.getType())) {
						bean.setIsLog(false);
					}

					bean.update();
					// 更新所有下级项目的状态与当前状态一致
					JfsaResourceController.this.resourceService.updateStatus(bean, bean.getStatus());
				}

				// 更新父对象的子对象ID列表
				JfsaResourceController.this.resourceService.updateChildredIds(parent);
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式查询
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("jfsaResource")
	public void ajaxSearch () {
		SqlPara sqlPara = Db.getSqlPara("system.findResource", this.getParaMapToKv());
		List<JfsaResource> list = JfsaResource.DAO.find(sqlPara);
		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(list));
	}

	@Before ({
		POST.class, EvictInterceptor.class
	})
	@CacheName ("jfsaResource")
	public void ajaxSwitchEnabledLog () {
		Integer id = this.getParaToInt("id");
		JfsaResource bean = JfsaResource.DAO.findById(id);

		if (bean == null) {
			this.renderAjaxFailed("1", "记录不存在!");
			return;
		}

		bean.setIsLog(!bean.getIsLog()).update();
		// 将状态返回
		this.renderAjaxSuccessed(Kv.by("isLog", bean.getIsLog()));
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit () {
		JfsaResource bean = JfsaResource.DAO.findById(this.getParaToInt("id"));
		JfsaResource parent = JfsaResource.DAO.findById(bean.getParentId());

		if (parent != null) {
			bean.put("parent_name", parent.getName());
		}

		// 查询目标记录
		this.setAttr("resource", bean);
	}

	/**
	 * 跳转到列表页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("jfsaResource")
	@Override
	public void index () {}

	/**
	 * 跳转到查看页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("jfsaResource")
	public void view () {
		JfsaResource bean = JfsaResource.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		JfsaResource parent = JfsaResource.DAO.findById(bean.getParentId());

		if (parent != null) {
			bean.put("parent_name", parent.getName());
		}

		this.setAttr("resource", bean);
	}

}
